#!/bin/bash
# function
usage() {
    cat <<EO_ECHO 1>&2
Usage: ${0##*/} -i FILE.log_a -o FILE.dat [OPTIONS] [FILE_LIST]
  -i, --input=FILE.log_a  Input logs, multiple occurences accepted
  -o, --output=FILE.dat   Output file, overwrite if exists!
  -q, --sql=FILE.sql      SQL source for MySQL's \`source FILE' command
  -n, --names=NAMES.csv   Names file, see \`--read-names'
  -x, --test=NUMBER       Test mode, only parse up to NUMBER dies

  -I, --interactive       Use interactive prompt mode to edit new data
                          item names
  -R, --read-names        Read names from an edited .csv log struct file,
                          see \`--names'

NOTE:
    DO NOT use file names containing spaces, which would cause problems
    for the scripts.
EO_ECHO
    exit 0
}

## options parsing
parsed=$(getopt --shell bash --name ${0##*/} \
    --options w:l:s:n:gGdymh \
    --longoptions wafer:,lot:,gendata,gendata2,distribution,yield,map,help \
    -- "$@")
if [[ $? -ne 0 ]]; then
    echo "error when parsing options, quit..." 1>&2
    exit 1
fi
echo parsed string: 1>&2
echo [$parsed] 1>&2
eval set -- "$parsed"
echo "Now the command line arguments:" 1>&2
echo "$@" 1>&2
echo arg1: [$1], arg2: [$2], arg3: [$3], arg4: [$4] ... 1>&2
while true; do
    case "$1" in
        -h|--help  ) usage ;;
        -i|--input ) input="$input $2"; shift 2 ;;
        -o|--output) output=$2;         shift 2 ;;
        -q|--sql   ) sql=$2;            shift 2 ;;
        -n|--names ) names=$2;          shift 2 ;;
        -x|--test  ) test=$2;           shift 2 ;;
        --         ) shift; break ;;
        *)
        echo "ERROR: unknown option: \`$arg'" 1>&2
        echo "Try run the script with argument \`-?' or \`--help'" 1>&2
        exit -1
        ;;
    esac
done
input="$input $*"
echo "Input:  [$input]"
echo "Output: [$output]"
echo "SQL:    [$sql]"
echo "Names:  [$names]"
echo "Test:   [$test]"
input_examine=$(echo $input)
if [ -z "$input_examine" -o -z "$output" ]; then
    echo "ERROR: You must specify both INPUT and OUTPUT." 1>&2
    usage
fi
